package com.wn.ticket.web.backstage;

import com.wn.ticket.common.PageBean;
import com.wn.ticket.common.ResponseEntity;
import com.wn.ticket.entity.*;
import com.wn.ticket.mapper.ArtistMapper;
import com.wn.ticket.mapper.DistrictMapper;
import com.wn.ticket.mapper.PerformAddressMapper;
import com.wn.ticket.service.PerformService;
import com.wn.ticket.vo.PerformVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author wuqingting
 * @date 2022/8/29
 */
@RestController
@RequestMapping("/backstage/perform")
public class PerformController {
    @Autowired
    private PerformService performService;
    @Autowired
    private DistrictMapper districtMapper;
    @Autowired
    private PerformAddressMapper performAddressMapper;
    @Autowired
    private ArtistMapper artistMapper;

    @Value("${upfile.performImg}")
    private String performImgPath;

    @PreAuthorize("hasAnyAuthority('super')")
    @PostMapping("/upload")
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        if (file == null || file.getOriginalFilename().lastIndexOf(".") == -1)//如果文件不存在或者没有文件类型
            return new ResponseEntity<>("400", "fail", "文件为空");

        ClassPathResource classPathResource = new ClassPathResource(performImgPath);//项目静态资源路径位置
        String resource = classPathResource.getURL().getPath();//项目静态资源路径位置

        String uid = UUID.randomUUID().toString().replace("-", "");//随机文件名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//去掉文件名,保留文件类型
        File newFile = new File(resource + "/" + uid + suffix);
        try {
            file.transferTo(newFile);
            return new ResponseEntity<>("200", "ok", newFile.getName());
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResponseEntity.fail;
    }

    @GetMapping("/getAll")
    public ResponseEntity getAll() {
        List<Perform> list = performService.getAll();

        return new ResponseEntity(list);
    }

    @GetMapping("/getById/{id}")
    public ResponseEntity getById(@PathVariable int id) {
        Perform perform = performService.getId(id);
        //艺人名转换为前端显示的格式
        List<Artist> artistList = perform.getArtistList();
        String artistNames="";
        for (Artist artist:artistList){
            artistNames+=artist.getName()+",";
        }
        artistNames=artistNames.substring(0,artistNames.length()-1);//去掉最后一个逗号
        artistList.get(0).setName(artistNames);
        perform.setArtistList(artistList);
        //门票转化为前端显示格式
        List<EntranceTicket> entranceTicketList = perform.getEntranceTicketList();
        String entranceTicketNames="";
        for (EntranceTicket ticket:entranceTicketList){
            entranceTicketNames+=ticket.getGrade()+","+ticket.getPrice().toString()+","+ticket.getNumber()+";";
        }
        entranceTicketList.get(0).setGrade(entranceTicketNames);
        perform.setEntranceTicketList(entranceTicketList);

        return new ResponseEntity(perform);
    }

    @PostMapping("/getPage")
    public ResponseEntity getPage(@RequestBody PerformVo performVo) {
        PageBean<Perform> pageBean = (PageBean<Perform>) performService.getPageByCondition(performVo.getPerform(), performVo.getCurrPage(), performVo.getPageSize());

        return new ResponseEntity(pageBean);
    }

    @PostMapping("/getOrderBy")
    public ResponseEntity getOrderBy(@RequestBody PerformVo performVo) {
        List<Perform> list = performService.getOrderByPrice(performVo.getPerform(), performVo.getOrderBy());

        return new ResponseEntity(list);
    }

    @PreAuthorize("hasAnyAuthority('super')")
    @PostMapping("/add")
    public ResponseEntity add(@RequestBody Perform perform) {
        District district = districtMapper.selectByNameAndType(perform.getDistrict().getName(), 2);
        perform.setDistrict(district);

        PerformAddress performAddress = performAddressMapper.getByName(perform.getPerformAddress().getName());
        if (performAddress!=null)
            perform.setPerformAddress(performAddress);

        String s = perform.getEntranceTicketList().get(0).getGrade();
        String[] split = s.split(";");
        ArrayList<EntranceTicket> entranceTicketList = new ArrayList<>();
        for (String ticket : split) {
            String[] split1 = ticket.split(",");
            BigDecimal bigDecimal = new BigDecimal(split1[1]);
            Integer integer = new Integer(split1[2]);
            EntranceTicket entranceTicket = new EntranceTicket();
            entranceTicket.setGrade(split1[0]);
            entranceTicket.setPrice(bigDecimal);
            entranceTicket.setNumber(integer);
            entranceTicket.setInitNumber(integer);
            entranceTicketList.add(entranceTicket);
        }
        perform.setEntranceTicketList(entranceTicketList);

        String name = perform.getArtistList().get(0).getName();
        boolean b = name.contains("，");
        String[] strings = name.split(b ? "，" : ",");
        ArrayList<Artist> artistList = new ArrayList<>();
        for (String s1 : strings) {
            Artist artist = artistMapper.getByName(s1);
            artistList.add(artist);
        }
        perform.setArtistList(artistList);


        performService.add(perform);
        return ResponseEntity.success;
    }

    @PreAuthorize("hasAnyAuthority('super')")
    @PostMapping("/update")
    public ResponseEntity update(@RequestBody Perform perform) {
        District district = districtMapper.selectByNameAndType(perform.getDistrict().getName(), 2);
        perform.setDistrict(district);

        PerformAddress performAddress = performAddressMapper.getByName(perform.getPerformAddress().getName());
        if (performAddress!=null)
            perform.setPerformAddress(performAddress);

        String s = perform.getEntranceTicketList().get(0).getGrade();
        String[] split = s.split(";");
        ArrayList<EntranceTicket> entranceTicketList = new ArrayList<>();
        for (String ticket : split) {
            String[] split1 = ticket.split(",");
            BigDecimal bigDecimal = new BigDecimal(split1[1]);
            Integer integer = new Integer(split1[2]);
            EntranceTicket entranceTicket = new EntranceTicket();
            entranceTicket.setGrade(split1[0]);
            entranceTicket.setPrice(bigDecimal);
            entranceTicket.setNumber(integer);
            entranceTicket.setInitNumber(integer);
            entranceTicketList.add(entranceTicket);
        }
        perform.setEntranceTicketList(entranceTicketList);

        String name = perform.getArtistList().get(0).getName();
        boolean b = name.contains("，");
        String[] strings = name.split(b ? "，" : ",");
        ArrayList<Artist> artistList = new ArrayList<>();
        for (String s1 : strings) {
            Artist artist = artistMapper.getByName(s1);
            artistList.add(artist);
        }
        perform.setArtistList(artistList);


        performService.update(perform);
        return ResponseEntity.success;
    }

    @PostMapping("/getCity")
    public ResponseEntity getCity(@RequestBody Perform perform) {
        District district = districtMapper.selectByNameAndType(perform.getDistrict().getName(), 2);
        if (district == null) {
            return ResponseEntity.fail;
        }

        return new ResponseEntity(district);
    }

    @PostMapping("/getPerformAddress")
    public ResponseEntity getPerformAddress(@RequestBody Perform perform) {
        PerformAddress performAddress = performAddressMapper.getByName(perform.getPerformAddress().getName());
        if (performAddress == null) {
            return ResponseEntity.fail;
        }

        return new ResponseEntity(performAddress);
    }

    @PostMapping("/getArtist")
    public ResponseEntity getArtist(@RequestBody Perform perform) {
        String name = perform.getArtistList().get(0).getName();
        boolean b = name.contains("，");
        String[] strings = name.split(b ? "，" : ",");
        for (String s : strings) {
            Artist artist = artistMapper.getByName(s);
            if (artist == null) {
                return new ResponseEntity("400", "艺人:" + s + "不存在", null);
            }
        }

        return ResponseEntity.success;
    }

    @PostMapping("/getTicket")
    public ResponseEntity getTicket(@RequestBody Perform perform) {
        String s = perform.getEntranceTicketList().get(0).getGrade();
        String[] split = s.split(";");
        for (String ticket : split) {
            String[] split1 = ticket.split(",");
            if (split1.length != 3) {
                return new ResponseEntity("400", "格式错误", null);
            }
            try {
                new BigDecimal(split1[1]);//检查格式
                new Integer(split1[2]);//检查格式
            } catch (NumberFormatException e) {
                return new ResponseEntity("400", "格式错误", null);
            }
        }

        return ResponseEntity.success;
    }

    @PostMapping("/getByName")
    public ResponseEntity getByName(@RequestBody Perform perform) {
        PageBean<Perform> pageBean = performService.getPageByCondition(perform, 1, 1);
        if (pageBean.getData().size() != 1) {
            return ResponseEntity.fail;
        }

        return new ResponseEntity(pageBean.getData().get(0));
    }

}
